package com.peanut.util;

import com.alibaba.fastjson.JSONObject;
import com.peanut.domain.po.TabUser;
import com.peanut.service.UserManagerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import java.util.List;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;


public class ShiroRealm extends AuthorizingRealm {


    @Resource
    private UserManagerService userService;
    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法");
        TabUser person = (TabUser) SecurityUtils.getSubject().getPrincipal();
        TabUser perms =  userService.selectBtPid(person.getUserId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String parse =(String) JSONObject.parse(String.valueOf(perms));
        info.addStringPermission(parse);
        return info;
    }
    //认证方法(登录)
     @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
         System.out.println("进入登录方法");

         UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
         TabUser tbUser =userService.login(token.getUsername());
         if(tbUser==null){
             return null;
         }
         //1表示登陆成功的对象,2数据库中的密码,3.盐 4用户的真实名字
       return new SimpleAuthenticationInfo(tbUser,tbUser.getUserId(), ByteSource.Util.bytes(tbUser.getJurisdiction()),tbUser.getUserName());

    }
}
